-- UISkyStoreItem
-- Created by huanghr
-- 使用宝罐界面


require "game/ui/form/sky_city/UIBuySkyItem"

UISkyStoreItem = class("UISkyStoreItem", function()
    return cc.Layer:create();
end);

function UISkyStoreItem.create(goodsId, type, args)
    return UISkyStoreItem.new(goodsId, type, args);
end

-- 构造函数
function UISkyStoreItem:ctor(goodsId, type, args)
    self:setName("UISkyStoreItem");
    self.goodsId = goodsId;
    self.type = type;
    self.args = args;

    -- 初始化
    local node = cc.CSLoader:createNode("layout/shop/UsePuzzle.csb");
    self:addChild(node);
    self.node = node;

    local canUse = SkyResourceM.query(goodsId, "can_use");
    self.canUse = canUse;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册各种点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize(node);
end

-- 注册点击事件
function UISkyStoreItem:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyStoreItem");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 使用个数按钮文本
    local str = getLocStr("btn_text_use_amount");
    -- 注册使用按钮点击事件
    local btnUse = findChildByName(self.node, "CT/btn_use_one");
    local function onUseClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 尝试使用
            self:tryUse(1);
        end
    end
    btnUse:addTouchEventListener(onUseClick);
    TextStyleM.setTextStyle(btnUse, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnUse:setTitleText(string.format(str, 1));

    -- 注册使用按钮点击事件
    local btnUseMulti = findChildByName(self.node, "CT/btn_use_multi");
    local function onUseClick2(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 尝试使用
            self:tryUse(5);
        end
    end
    btnUseMulti:addTouchEventListener(onUseClick2);
    TextStyleM.setTextStyle(btnUseMulti, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnUseMulti:setTitleText(string.format(str, 5));

    -- 注册购买按钮
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    local function onBuy(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            if self.type == "robot" then
                -- 分解

                local function okFunc()
                    -- 开始收集奖励礼包
                    BonusM.clearBonusCollect();
                    BonusM.startBonusCollect();

                    -- 直接尝试分解
                    local ret = SkyRobotM.splitRobot(self.goodsId, 1);

                    BonusM.endBonusCollect();

                    local bonusList = table.deepcopy(BonusM.getBonusCollect());
                    BonusM.clearBonusCollect();

                    if ret ~= true then
                        if type(ret) == "string" then
                            alert(getLocStr(ret));
                        end
                    else
                        -- 弹出奖励提示框
                        if #bonusList > 0 then
                            showBonusNotifyForm(getLocStr("sky_city_guaide_bonus_title"), bonusList);
                        end

                        UIMgr:getCurrentScene():removeFormByName("UISkyStoreItem");
                    end
                end

                -- 目前只有遗迹碎片，先写死了
                local split = SkyRobotM.query(self.goodsId, "split");
                if type(split[1]) == "table" then
                    local bonusNum = split[1][3];
                    confirm2(CONFIRM_TYPE_OK_CANCEL, getLocStr("split"),
                            string.format(getLocStr("split_desc"), bonusNum), okFunc);
                end

            elseif self.type == "stone" then
                -- 分解
                -- 弹出奖励提示框
                local function okFunc()
                    -- 开始收集奖励礼包
                    BonusM.clearBonusCollect();
                    BonusM.startBonusCollect();

                    -- 直接尝试分解
                    local ret = SkyStoneM.splitStone(self.goodsId, 1);

                    BonusM.endBonusCollect();

                    local bonusList = table.deepcopy(BonusM.getBonusCollect());
                    BonusM.clearBonusCollect();

                    if ret ~= true then
                        if type(ret) == "string" then
                            alert(getLocStr(ret));
                        end
                    else
                        if #bonusList > 0 then
                            showBonusNotifyForm(getLocStr("sky_city_guaide_bonus_title"), bonusList);
                        end

                        UIMgr:getCurrentScene():removeFormByName("UISkyStoreItem");
                    end

                end

                -- 目前只有遗迹碎片，先写死了
                local split = SkyStoneM.query(self.goodsId, "split");
                local bonusNum = split[1][3];
                confirm2(CONFIRM_TYPE_OK_CANCEL, getLocStr("split"),
                        string.format(getLocStr("split_desc"), bonusNum), okFunc);

            else
                -- 打开购买页面
                UIMgr:getCurrentScene():removeFormByName("UIBuySkyItem");
                local uiForm = UIBuySkyItem.create(self.goodsId);
                UIMgr:getCurrentScene():addForm(uiForm);
                UIMgr:getCurrentScene():removeFormByName("UISkyStoreItem");
            end
        end
    end
    btnBuy:addTouchEventListener(onBuy);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    if self.type == "robot" or self.type == "stone" then
        btnBuy:setTitleText(getLocStr("btn_text_resolve"));
    else
        btnBuy:setTitleText(getLocStr("btn_text_buy"));
    end

    -- 注册背景点击事件
    local bgImg = findChildByName(self.node, "bg/bgImg");
    local function onBgClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyStoreItem");
        end
    end
    bgImg:addTouchEventListener(onBgClick);
end

-- 注册事件处理回调函数
function UISkyStoreItem:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UISkyStoreItem 界面析构清理");
            EventMgr.removeAll("UISkyStoreItem");
            local uiForm = UIMgr:getCurrentScene():getFormByName("UISkyResource");
            if uiForm then
                uiForm:refreshItem();
            end
        elseif ev == "enter" then

        end
    end);

    -- 购买商品事件回调
    EventMgr.register("UISkyStoreItem", event.BUY_SKY_RESOURCE_ITEM, function(args)
        self.canUse = 1;
        self:redraw();
    end);

    EventMgr.register("UISkyStoreItem", event.USE_SKY_CITY_RESOURSE, function(args)
        self:applyEffect(args.goodsId, args.amount, args.bonusList);
    end);
end

-- 重绘
function UISkyStoreItem:redraw()
    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("name");

    -- 获取商品信息
    local itemName;
    local desc = "";
    local detail = "";
    local extra = "";

    if self.type == "robot" then
        itemName = SkyRobotM.query(self.goodsId, "name");
        desc = SkyRobotM.query(self.goodsId, "desc");
        detail = SkyRobotM.query(self.goodsId, "prop_desc");

        local info = SkyRobotM.getRobotInfo(self.goodsId);
        detail = detail .. "\n" .. string.format(getLocStr("robot_num_desc"), info["fighting"], info["total"] - info["fighting"]);
    else
        itemName = ItemM.query(self.goodsId, "name");
        desc = ItemM.getItemDesc(self.goodsId);
        detail = ItemM.getItemDetail(self.goodsId);

        local stoneStyle = SkyStoneM.query(self.goodsId, "style");
        if stoneStyle then
            -- 如果是符石，则描述里面要加一些内容
            extra = string.format(getLocStr("stone_detail"), getLocStr("stone_style_" .. stoneStyle));
        end
    end

    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(itemName);

    -- 商品描述
    local descLabel = findChildByName(CT, "desc");
    local detailLabel = findChildByName(CT, "detail");
    local extraLabel = findChildByName(CT, "extra");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    TextStyleM.setTextStyle(detailLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    TextStyleM.setTextStyle(extraLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    descLabel:setString(desc);
    --detailLabel:setString(detail);
    detailLabel = applyString(detailLabel, detail);
    extraLabel = applyString(extraLabel, extra);

    -- 按钮置灰判断
    local btnOne = findChildByName(CT, "btn_use_one");
    local btnMulti = findChildByName(CT, "btn_use_multi");
    local btnBuy = findChildByName(CT, "btn_buy");
    btnBuy:setVisible(false);

    if self.type == "robot" then
        -- 机器人的话显示 "分解" 按钮
        btnOne:setVisible(false);
        btnMulti:setVisible(false);

        btnBuy:setVisible(true);

        -- 没有分解奖励，隐藏分解按钮
        local split = SkyRobotM.query(self.goodsId, "split");
        if type(split) ~= "table" or #split == 0 then
            btnBuy:setVisible(false);
        end

        -- 如果是描述用的就不显示
        if self.args and self.args["robot_tip"] then
            btnBuy:setVisible(false);
        end
    elseif self.type == "stone" then
        -- 符石显示分解按钮
        btnOne:setVisible(false);
        btnMulti:setVisible(false);

        btnBuy:setVisible(true);
    elseif self.canUse == 1 then
        btnOne:setVisible(true);
        btnMulti:setVisible(true);
        if ItemM.getAmount(ME.user, self.goodsId) >= 1 then
            btnOne:setBright(true);
            btnOne:setTouchEnabled(true);
        else
            btnOne:setBright(false);
            btnOne:setTouchEnabled(false);
        end

        if ItemM.getAmount(ME.user, self.goodsId) >= 5 then
            btnMulti:setBright(true);
            btnMulti:setTouchEnabled(true);
        else
            btnMulti:setBright(false);
            btnMulti:setTouchEnabled(false);
        end

        if ItemM.getAmount(ME.user, self.goodsId) < 1 then
            btnOne:setVisible(false);
            btnMulti:setVisible(false);

            if SkyResourceM.query(self.goodsId, "alias") == "energy" then
                btnBuy:setVisible(true);
            else
                btnOne:setVisible(false);
                btnMulti:setVisible(false);
            end
        end
    else
        btnOne:setVisible(false);
        btnMulti:setVisible(false);
    end

    local fixBottomFix = 0;

    -- 如果还未完成指引，按钮隐藏
    if not NewAirShipM.isFinishGuide() then
        btnBuy:setVisible(false);
        btnOne:setVisible(false);
        btnMulti:setVisible(false);
        fixBottomFix = 20;
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    local fixBottom = nil;
    local fixTop = nil;
    if self.priceType ~= "gem" then
        -- 自适应压缩/放大可能背景有差异，这个手动修改一下
        fixBottom = AlignM.getAdaptDefaultMargin() - 30;
        fixTop = AlignM.getAdaptDefaultMargin() - 10;
    end

    fixBottom = fixBottom + fixBottomFix + 10;

    if self.type == "robot" then
        AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, btnBuy}, {nil, nil, 30, }, fixTop, fixBottom);
    elseif self.type == "stone" then
        AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, extraLabel, btnBuy}, {nil, nil, nil, 30, }, fixTop, fixBottom);
    elseif self.canUse == 1 and ItemM.getAmount(ME.user, self.goodsId) < 1 then
        AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, btnBuy}, {nil, nil, 30, }, fixTop, fixBottom);
    else
        AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
            { nameLabel, descLabel, detailLabel, btnOne}, {nil, nil, 30, }, fixTop, fixBottom);
        btnMulti:setPositionY(btnOne:getPositionY());
    end

    if self.type == "robot" or self.type == "stone" then
        local starNode = findChildByName(self.node, "CT/star_node");
        local rank = 0;
        if self.type == "robot" then
            rank = SkyRobotM.query(self.goodsId, "rank");
        else
            rank = ItemM.query(self.goodsId, "rank");
        end
        local starLayer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");
        if starLayer ~= nil then
            starNode:addChild(starLayer);
        end
        -- 星级节点的纵坐标要与名称保持一致
        starNode:setPositionY(nameLabel:getPositionY() + 5);
        starNode:setVisible(true);
    end
end

-- 适配
function UISkyStoreItem:resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg")

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UISkyStoreItem:tryUse(amount)
    if ItemM.getAmount(ME.user, self.goodsId) < amount then
        showHint(string.format(getLocStr("no_enough_for_use"), ItemM.query(self.goodsId, "name")));
        return;
    end

    -- 开始收集奖励信息
    BonusM.clearBonusCollect();
    BonusM.startBonusCollect();
    -- 使用
    PropertyM.fastUse(self.goodsId, amount);

    -- 取得奖励列表，用于显示
    BonusM.endBonusCollect();
    local collectBonus = BonusM.getBonusCollect();
    BonusM.clearBonusCollect();

    -- 合并同类奖励
    local bonusList = {};
    local len = #collectBonus;
    for i = 1, len do
        if collectBonus[i] then
            for j = i+1, len do
                if collectBonus[j] and collectBonus[i][1] == collectBonus[j][1] and collectBonus[i][2] == collectBonus[j][2] then
                    -- bonus[1]和bonus[2]都相同的合并
                    collectBonus[i][3] = collectBonus[i][3] + collectBonus[j][3];
                    collectBonus[j] = nil;
                end
            end
            table.insert(bonusList,collectBonus[i]);
        end
    end

    EventMgr.fire(event.USE_SKY_CITY_RESOURSE, {["goodsId"] = self.goodsId, ["bonusList"] = bonusList, ["amount"] = amount, });
end

-- 道具使用后的回调
function UISkyStoreItem:applyEffect(classId, amount, bonusList)
    -- 播放物品获得奖励提示
    if SkyResourceM.query(classId, "alias") == "energy" then
        alert(string.format(getLocStr("energy_bonus"), ME.user.dbase:query("ship_energy", 0)));
    else
        showBonusNotifyForm(ItemM.query(classId, "name"), bonusList, nil, nil, getLocStr("btn_text_ok"));
    end

    -- 如果已经都用完了，那么直接关闭界面
    if ItemM.getAmount(ME.user, classId) <= 0 then
        UIMgr.getCurrentScene():removeFormByName("UISkyStoreItem");
    else
        self:redraw();
    end
end